<?php
/*
 * @Created by: wangchengcheng
 * @Author: wangchengcheng
 * @Date: 2020-01-07 21:42:47
 * @LastEditors  : wangchengcheng
 * @LastEditTime : 2020-01-14 20:30:32
 */

namespace App\Observers;

use AipImageCensor;
use App\Models\Article;
use App\Models\Comment;
use Notification;
use Str;
use App\Notifications\Comment as CommentNotification;
use App\Models\SocialiteUser;
use Log;

class CommentObserver extends BaseObserver
{
    public function creating($comment)
    {
        $baiduConfig = [
            config('services.baidu.appid'),
            config('services.baidu.appkey'),
            config('services.baidu.secret'),
        ];

        if(Str::isTrue(config('wblog.comment_audit')) && count(array_filter($baiduConfig)) === 3){
            $baiduClient = new AipImageCensor(
                config('services.baidu.appid'), 
                config('services.baidu.appkey'),
                config('services.baidu.secret')
            );
            $result = $baiduClient->antiSpam($comment->content);

            //spam=0 audited
            if(isset($result['result']['spm'])){
            	$comment->is_audited = $result['result']['spm'] === 0 ? 1 : 0;
            }else{
            	$comment->is_audited = 0;
            	Log::error('error: ' . json_encode($result) );
            }
            
        }
    }

    public function created($comment)
    {
        parent::created($comment);

        if(mail_is_configured()){
            $socialiteUser = auth()->guard('socialite')->user();
            $article = Article::withTrashed()->find($comment->article_id);

            //Send email to admin 如果当前评论的人不是管理员就发送邮件
            if($socialiteUser->is_admin === 0){
                Notification::route(
                    'mail',
                    config('wblog.notification_email')
                )->notify(new CommentNotification($socialiteUser, $article, $comment));
            }


            if(intval($comment->pid) !== 0 ){
                $parentComment = Comment::find($comment->pid);
                if($socialiteUser->id !== $parentComment->socialite_user_id){
                    //Send email to socialite user
                    $parentComment->socialiteUser->notify(new CommentNotification($socialiteUser, $article, $comment));
                }
               
            }

        }
    }
}
